package cn.edu.hbwe.book.servlet.cilent;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;

import cn.edu.hbwe.book.entity.User;
import cn.edu.hbwe.book.exception.RegisterException;
import cn.edu.hbwe.book.service.UserService;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1.检验验证码
				String userCode = request.getParameter("userCode");
				String serverCode = (String) request.getSession().getAttribute("serverCode");
				if (!serverCode.equalsIgnoreCase(userCode)) {
					request.setAttribute("codeError", "输入验证码错误");
					request.getRequestDispatcher("/client/register.jsp").forward(request, response);
					return;
				}
		// 2.封装注册参数到user
				User user = new User();
				try {
					BeanUtils.populate(user, request.getParameterMap());
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
		// 3.调用UserServive的注册方法
				UserService service = new UserService();
				try {
					service.register(user);
					//注册成功，跳转到成功页面
					response.sendRedirect(request.getContextPath()+"/client/registersuccess.jsp");
				} catch (RegisterException e) {
					// TODO Auto-generated catch block
					String error = e.getMessage();//注册失败
					response.getWriter().write(error);
				}
			}
	}


